package cn.com.infohold.smartcity.api;

import com.google.gson.Gson;

import java.io.IOException;
import cn.com.infohold.smartcity.api.converter.JsonConverter;
import cn.com.infohold.smartcity.api.converter.XmlConverter;
import library.http.Http;
import library.http.HttpAdapter;
import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * Created by Mr.Fan on 2017/3/25.
 */

public class SDK {
    private static API api;
    private static FileAPI fileAPI;
    private static final JsonConverter jsonConverter = new JsonConverter();
    private static final XmlConverter xmlConverter = new XmlConverter();

    public static Gson getGson() {
        return jsonConverter.getGson();
    }

    public static JsonConverter getJsonConverter() {
        return jsonConverter;
    }

    public static XmlConverter getXmlConverter() {
        return xmlConverter;
    }

    private static HttpAdapter getAdapter() {
        HttpAdapter adapter = new HttpAdapter();
        adapter.addConverter(jsonConverter);
        adapter.addConverter(xmlConverter);
        return adapter;
    }

    public static API api() {
        if (api == null) {
            synchronized (SDK.class) {
                if (api == null) {
                    api = Http.load(API.class, getAdapter());
                }
            }
        }
        return api;
    }

    public static FileAPI fileAPI() {
        if(fileAPI==null){
            synchronized (SDK.class) {
                if (fileAPI == null) {
                    fileAPI = Http.load(FileAPI.class, getAdapter());
                }
            }
        }
        return fileAPI;
    }

    private static final class CacheInterceptor implements Interceptor {
        private final int maxAge;
        private final boolean force;

        private CacheInterceptor(boolean force, int maxAge) {
            this.maxAge = maxAge;
            this.force = force;
        }


        @Override
        public Response intercept(Chain chain) throws IOException {
            Response origin = chain.proceed(chain.request());
            return origin.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public,max-age=" + maxAge + (force ? ",only-if-cached" : ""))
                    .build();
        }

    }
}
